package com.igeek.ssm.service;

import com.github.pagehelper.PageHelper;
import com.igeek.ssm.mapper.UserMapper;
import com.igeek.ssm.pojo.User;
import com.igeek.ssm.pojo.UserExample;
import com.igeek.ssm.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Calendar;
import java.util.List;

/**
 * @Description TODO
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/1/12 15:36
 */
@Service
public class UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    //登录
    public User login(LoginVO vo) {
        //封装条件对象
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        //封装姓名
        criteria.andNameEqualTo(vo.getName());
        //封装密码
        criteria.andPwdEqualTo(vo.getPwd());
        //执行查询
        List<User> users = userMapper.selectByExample(userExample);
        return users.size()>0?users.get(0):null;
    }

    //注册
    public boolean register(User user) {
        //计算年龄
        Calendar c = Calendar.getInstance();
        c.setTime(user.getBirthday());
        int age = LocalDate.now().getYear() - c.get(Calendar.YEAR);
        user.setAge(age + 1);
        //状态
        user.setState("0");
        //执行非空插入操作
        int i = userMapper.insertSelective(user);
        return i>0?true:false;
    }

    //根据条件分页查询用户列表
    public List<User> viewAllByQuery(int current , String query){
        //封装查询条件
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andNameLike("%"+query+"%");

        //PageHelper的分页插件
        //第一个参数：当前页码  第二个参数：每页展示的记录数
        PageHelper.startPage(current , 3);

        //执行Mapper接口的查询操作
        List<User> list = userMapper.selectByExample(userExample);
        return list;
    }

    //删除操作
    public boolean delete(int id) {
        int i = userMapper.deleteByPrimaryKey(id);
        return i>0?true:false;
    }

    //根据ID查询用户信息
    public User viewOne(int id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    //更新用户
    public boolean update(User user) {
        //计算年龄
        Calendar c = Calendar.getInstance();
        c.setTime(user.getBirthday());
        int age = LocalDate.now().getYear() - c.get(Calendar.YEAR);
        user.setAge(age + 1);
        //执行非空插入操作
        int i = userMapper.updateByPrimaryKeySelective(user);
        return i>0?true:false;
    }
}
